package com.ztgf.commodity.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommodityEvaluationMapper;
import com.ztgf.commodity.models.bo.*;
import com.ztgf.commodity.models.dto.CommodityEvaluationDTO;
import com.ztgf.commodity.models.service.ICommodityEvaluationService;
import com.ztgf.commodity.models.vo.*;
import com.ztgf.order.models.dto.OrderStatusDTO;
import com.ztgf.order.models.service.IOrderStatusService;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * 商品评价表控制器
 *
 * @author chenyu.wang
 * @Date 2020-05-29 15:18:55
 */
@Slf4j
@DubboService
public class CommodityEvaluationServiceImpl extends ServiceImpl<CommodityEvaluationMapper, CommodityEvaluationDTO> implements ICommodityEvaluationService {

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IOrderStatusService orderStatusService;

    private static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";

    private static final SimpleDateFormat SDF = new SimpleDateFormat(DATEFORMAT);


    @Override
    public boolean add(CommodityEvaluationSaveBO saveBO) {
        CommodityEvaluationDTO dto = new CommodityEvaluationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);

        //计算好评or差评
        //0评价、1回复、2追评 回复和追评没有星级
        if (saveBO.getType() == ZERO) {
            if (saveBO.getCommodityEvaluation() != null && saveBO.getServiceEvaluation() != null && saveBO.getLogisticsEvaluation() != null) {
                if (saveBO.getLogisticsEvaluation() + saveBO.getServiceEvaluation() + saveBO.getCommodityEvaluation() > 11) {
                    //12星算好评
                    dto.setCompositeEvaluation(ZERO);//综合评价 0好评，1差评
                } else {
                    dto.setCompositeEvaluation(ONE);//综合评价 0好评，1差评
                }
            }
        }
        return this.insert(dto);
    }

    @Override
    public Integer getCommentsNumber(Long id) {
        return baseMapper.getCommentsNumber(id);
    }

    @Override
    public Page<CommodityEvaluationPageVO> queryEvaluationList(CommodityEvaluationBO bo) {
        Page<CommodityEvaluationPageVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityEvaluationPageVO> list = baseMapper.queryEvaluationList(page, bo);
        page.setRecords(list);
        return page;
    }

    @Override
    public String getShopPraise(Long shopId) {
        Wrapper<CommodityEvaluationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("status", ZERO);//状态 0正常、1删除
        wrapper.eq("type", ZERO);//类型 0评价、1回复、2追评

        Integer praise = 0;
        List<CommodityEvaluationDTO> commodityEvaluationDTOList = this.selectList(wrapper);

        if (commodityEvaluationDTOList.size() <= 0) {
            return "1";
        }

        for (CommodityEvaluationDTO dto : commodityEvaluationDTOList) {
            if (dto.getCompositeEvaluation() == 0) {
                //综合评价 0好评，1差评
                praise++;
            }
        }

        if (praise.equals(0)) {
            return "0";
        }

        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        return df.format((float) praise / commodityEvaluationDTOList.size());
    }

    @Override
    public CommodityEvaluationScoreVO getShopScore(Long shopId) {
        CommodityEvaluationScoreVO commodityEvaluationScoreVO = new CommodityEvaluationScoreVO();
        Wrapper<CommodityEvaluationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("seller_shop_id", shopId);
        wrapper.eq("status", 0);//状态 0正常、1删除
        wrapper.eq("type", 0);//类型 0评价、1回复、2追评
        List<CommodityEvaluationDTO> commodityEvaluationDTOList = this.selectList(wrapper);
        if (isNull(commodityEvaluationDTOList)) {
            //没有评价，默认为0
            commodityEvaluationScoreVO.setCommodityEvaluation("5");//商品评分
            commodityEvaluationScoreVO.setLogisticsEvaluation("5");//物流评分
            commodityEvaluationScoreVO.setServiceEvaluation("5");//服务态度评分
            return commodityEvaluationScoreVO;
        }
        int cEvaluation = 0; //商品评价
        int lEvaluation = 0; //物流评价
        int sEvaluation = 0; //商品评价
        for (CommodityEvaluationDTO dto : commodityEvaluationDTOList) {
            cEvaluation = cEvaluation + dto.getCommodityEvaluation();//商品评价相加
            lEvaluation = lEvaluation + dto.getLogisticsEvaluation();//物流评价相加
            sEvaluation = sEvaluation + dto.getServiceEvaluation();//服务态度相加
        }
        int totalScore = commodityEvaluationDTOList.size();
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        commodityEvaluationScoreVO.setCommodityEvaluation(df.format((float) cEvaluation / totalScore));//商品评分
        commodityEvaluationScoreVO.setLogisticsEvaluation(df.format((float) lEvaluation / totalScore));//物流评分
        commodityEvaluationScoreVO.setServiceEvaluation(df.format((float) sEvaluation / totalScore));//服务态度评分
        return commodityEvaluationScoreVO;
    }

    @Override
    public boolean addEvaluation(CommodityAddEvaluationBO bo) {
        log.info("评价内容 : {}", bo);
        CommodityEvaluationDTO saveDto = new CommodityEvaluationDTO();
        saveDto.setId(ymlConfig.getPkId());
        if (bo.getSellerShopId() != null) {
            saveDto.setSellerShopId(bo.getSellerShopId());
        }
        if (bo.getShopId() != null) {
            //店铺信息
            ShopInfoDTO shopInfo = shopInfoService.selectById(bo.getShopId());
            saveDto.setShopId(bo.getShopId());
            saveDto.setShopName(shopInfo.getName());
            saveDto.setShopUrl(shopInfo.getLogo());
        }
        if (StringUtils.isNotBlank(bo.getImgUrls())) {
            saveDto.setImgUrls(bo.getImgUrls());
            saveDto.setContentType(ONE);
        } else {
            saveDto.setContentType(ZERO);
        }
        if (StringUtils.isNotBlank(bo.getVideoUrls())) {
            saveDto.setVideoUrls(bo.getVideoUrls());
            saveDto.setContentType(TWO);
        }
        if (bo.getContent() != null) {
            saveDto.setContent(bo.getContent());
        } else {
            saveDto.setContent(EVALUATION_TEXT);
        }
        if (bo.getServiceEvaluation() != null) {
            saveDto.setServiceEvaluation(bo.getServiceEvaluation());
        }
        if (bo.getLogisticsEvaluation() != null) {
            saveDto.setLogisticsEvaluation(bo.getLogisticsEvaluation());
        }
        if (bo.getCommodityEvaluation() != null) {
            saveDto.setCommodityEvaluation(bo.getCommodityEvaluation());
        }
        //计算好评or差评
        //0评价、1回复、2追评 回复和追评没有星级
        log.info("评价类型 : {}", bo.getType());
        if (bo.getType() == ZERO) {
            if (bo.getCommodityEvaluation() != null && bo.getServiceEvaluation() != null && bo.getLogisticsEvaluation() != null) {
                //总评分
                int num = bo.getCommodityEvaluation() + bo.getServiceEvaluation() + bo.getLogisticsEvaluation();
                log.info("*****评价总评分***** : {}", num);
                if (num > FOURTEEN) {
                    //综合评价 0好评，1差评
                    saveDto.setCompositeEvaluation(ZERO);
                    saveDto.setStarLevel(FIVE);
                } else if (num >= TWELVE) {
                    saveDto.setCompositeEvaluation(ZERO);
                    saveDto.setStarLevel(FOUR);
                } else if (num >= NINE) {
                    saveDto.setCompositeEvaluation(ZERO);
                    saveDto.setStarLevel(THREE);
                } else if (num >= SIX) {
                    saveDto.setCompositeEvaluation(ONE);
                    saveDto.setStarLevel(TWO);
                } else if (num > ZERO) {
                    saveDto.setCompositeEvaluation(ONE);
                    saveDto.setStarLevel(ONE);
                } else {
                    saveDto.setCompositeEvaluation(ONE);
                    saveDto.setStarLevel(ZERO);
                }
            }
        }
        if (bo.getOrderId() != null) {
            saveDto.setOrderId(bo.getOrderId());
        }
        if (bo.getCommodityId() != null) {
            saveDto.setCommodityId(bo.getCommodityId());
        }
        if (bo.getType() != null) {
            saveDto.setType(bo.getType());
        }
        if (bo.getImpressionLabel() != null) {
            saveDto.setImpressionLabel(bo.getImpressionLabel());
        }
        boolean insert = this.insert(saveDto);
        if (!insert) {
            return false;
        }
        Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", bo.getOrderId());
        OrderStatusDTO statusDTO = orderStatusService.selectOne(wrapper);
        if (statusDTO != null) {
            OrderStatusDTO updateState = new OrderStatusDTO();
            updateState.setId(statusDTO.getId());
            updateState.setEvaluationState(ONE);
            boolean update = orderStatusService.updateById(updateState);
            if (!update) {
                throw new RuntimeException("修改订单评价状态失败!");
            }
        }
        return true;
    }

    @Override
    public boolean addChaseEvaluation(CommodityChaseBO bo) {
        //评价信息
        CommodityEvaluationDTO dto = this.selectById(bo.getEvaluationId());
        if (dto != null) {
            CommodityEvaluationDTO saveDto = new CommodityEvaluationDTO();
            saveDto.setId(ymlConfig.getPkId());
            saveDto.setShopId(dto.getShopId());
            saveDto.setShopName(dto.getShopName());
            saveDto.setShopUrl(dto.getShopUrl());
            saveDto.setImgUrls(bo.getImgUrls());
            saveDto.setVideoUrls(bo.getVideoUrls());
            saveDto.setContent(bo.getContent());
            saveDto.setContentType(bo.getContentType());
            saveDto.setOrderId(dto.getOrderId());
            saveDto.setCommodityId(dto.getCommodityId());
            saveDto.setType(bo.getType());
            saveDto.setParentId(dto.getId());
            return this.insert(saveDto);
        }
        return false;
    }

    @Override
    public boolean addEvaluationReply(CommodityEvaluationReplyBO bo) {
        //评价信息
        CommodityEvaluationDTO dto = this.selectById(bo.getEvaluationId());
        if (dto != null) {
            CommodityEvaluationDTO saveDto = new CommodityEvaluationDTO();
            saveDto.setId(ymlConfig.getPkId());
            saveDto.setSellerShopId(dto.getSellerShopId());
            saveDto.setContent(bo.getContent());
            saveDto.setContentType(bo.getContentType());
            saveDto.setOrderId(dto.getOrderId());
            saveDto.setCommodityId(dto.getCommodityId());
            saveDto.setType(bo.getType());
            saveDto.setParentId(dto.getId());
            return this.insert(saveDto);
        }
        return false;
    }

    @Override
    public Page<CommodityEvaluationManageVO> queryEvaluationManageList(CommodityEvaluationManageBO bo) {
        Page<CommodityEvaluationManageVO> pages = new Page<>(bo.getPageNo(), bo.getPageSize());
        log.info("评价查询参数 : {}", bo);
        List<CommodityEvaluationManageVO> list = baseMapper.queryEvaluationManageList(pages, bo);
        if (!isNull(list)) {
            for (CommodityEvaluationManageVO vo : list) {
                List<CommodityEvaluationPageVO> parentList = baseMapper.getByParentId(vo.getId());
                if (!isNull(parentList)) {
                    vo.setUnderList(parentList);
                }
            }
        }
        pages.setRecords(list);
        return pages;
    }

    @Override
    public CommodityEvaluationPageVO getViewEvaluationById(Long id) {
        return baseMapper.getViewEvaluationById(id);
    }

    @Override
    public Page<CommodityShopPageEvaluationVO> queryShopPageEvaluation(CommodityEvaluationManageBO bo) {
        Page<CommodityShopPageEvaluationVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityShopPageEvaluationVO> list = baseMapper.queryShopPageEvaluation(page, bo);
        page.setRecords(list);
        return page;
    }

    /*
     * @description:获取发起评价页左侧商品订单信息
     * @author: chenyu.wang
     * @date: 2020-08-19
     */
    @Override
    public CommodityEvaluationOneVO queryLeftOrderMsg(Long id) {
        return baseMapper.queryLeftOrderMsg(id);
    }

    /*
     * @description:买家删除评价
     * @author: chenyu.wang
     * @date: 2020-08-20
     */
    @Override
    public boolean deleteEvaluation(Long shopId, Long id) {
        CommodityEvaluationDTO dto = this.selectById(id);
        if (dto == null) {
            return false;
        }
//        CommodityEvaluationDTO updateDto = new CommodityEvaluationDTO();
//        updateDto.setId(dto.getId());
//        updateDto.setStatus(ONE);//删除
//        updateDto.setUpdateUserId(shopId);
        boolean update = this.deleteById(dto);
        if (!update) {
            return false;
        }
        Wrapper<CommodityEvaluationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", id);
        List<CommodityEvaluationDTO> list = this.selectList(wrapper);
        if (isNull(list)) {
            return true;
        }
        baseMapper.delete(wrapper);
//        List<CommodityEvaluationDTO> updateList = new ArrayList<>();
//        for (CommodityEvaluationDTO evaluationDTO : list) {
//            CommodityEvaluationDTO dtoList = new CommodityEvaluationDTO();
//            dtoList.setId(evaluationDTO.getId());
//            dtoList.setStatus(ONE);
//            dtoList.setUpdateUserId(shopId);
//            updateList.add(dtoList);
//        }
        return true;
    }

    /*
     * @description:商城商品评价页，店铺全部评价列表
     * @author: chenyu.wang
     * @date: 2020-08-21
     */
    @Override
    public List<CommodityEvaluationTwoVO> queryShopAllEvaluation(Long shopId) {
        return baseMapper.queryShopAllEvaluation(shopId);
    }

    /*
     * @description:商城商品评价页头部数据
     * @author: chenyu.wang
     * @date: 2020-08-21
     */
    @Override
    public CommodityEvaluationThreeVO queryGoodsEvaluationHeader(Long goodsId) {
        CommodityEvaluationThreeVO vo = baseMapper.queryGoodsEvaluationHeader(goodsId);
        if (null == vo) {
            CommodityEvaluationThreeVO msg = baseMapper.getGoodsMsgById(goodsId);
            msg.setBuyNumber(0);
            msg.setPraiseRate("暂无评价!");
            msg.setAllNum(0);
            msg.setPerfectMatchNum(0);
            msg.setDurableNum(0);
            msg.setCostNum(0);
            msg.setPerformanceNum(0);
            msg.setCraftNum(0);
            msg.setLogisticsNum(0);
            msg.setGoodsQualityNum(0);
            msg.setStrongNum(0);
            return msg;
        } else {
            vo.setAllNum(this.goodsAllEvaluationNum(goodsId));//商品全部评价
            vo.setPerfectMatchNum(baseMapper.queryLabelNum("完美匹配", goodsId));//完美匹配
            vo.setDurableNum(baseMapper.queryLabelNum("安全耐用", goodsId));//安全耐用
            vo.setCostNum(baseMapper.queryLabelNum("性比价高", goodsId));//性价比高
            vo.setPerformanceNum(baseMapper.queryLabelNum("性能优良", goodsId));//性能优良
            vo.setCraftNum(baseMapper.queryLabelNum("工艺精致", goodsId));//工艺精致
            vo.setLogisticsNum(baseMapper.queryLabelNum("物流及时", goodsId));//物流及时
            vo.setGoodsQualityNum(baseMapper.queryLabelNum("质量不错", goodsId));//质量不错
            vo.setStrongNum(baseMapper.queryLabelNum("稳定性强", goodsId));//稳定性强
            //计算商品好评率 = 商品好评数量 / 商品全部评价数量
            NumberFormat percent = NumberFormat.getPercentInstance();
            percent.setMaximumFractionDigits(TWO);
            //全部评价
            BigDecimal all = new BigDecimal(this.goodsAllEvaluationNum(goodsId)).setScale(TWO, BigDecimal.ROUND_UP);
            //好评
            BigDecimal praise = new BigDecimal(this.goodsPraiseNum(goodsId)).setScale(TWO, BigDecimal.ROUND_UP);
            BigDecimal div = praise.divide(all, TWO).setScale(TWO, BigDecimal.ROUND_UP);
            log.info("全部评价数量 : {},好评数量 : {},好评率 : {}", all, praise, div);
            vo.setPraiseRate(percent.format(div));
            return vo;
        }
    }

    /*
     * @description:商品全部评价数量
     * @author: chenyu.wang
     * @date: 2020-08-21
     */
    private Integer goodsAllEvaluationNum(Long goodsId) {
        Wrapper<CommodityEvaluationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", ZERO);
        wrapper.eq("commodity_id", goodsId);
        return this.selectCount(wrapper);
    }

    /*
     * @description:商品好评数量
     * @author: chenyu.wang
     * @date: 2020-08-21
     */
    private Integer goodsPraiseNum(Long goodsId) {
        Wrapper<CommodityEvaluationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", ZERO);
        wrapper.eq("commodity_id", goodsId);
        wrapper.eq("composite_evaluation", ZERO);
        return this.selectCount(wrapper);
    }
}
